package com.frank.demo.io.netty.http;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import static io.netty.handler.codec.http.HttpResponseStatus.OK;

/**
 * Http Request Execution Handler
 *
 * @author biezhi
 * @date 2017/12/24
 */
@Slf4j
public class RequestExecution implements Runnable {

    private final ChannelHandlerContext ctx;
    private final FullHttpRequest fullHttpRequest;

    public RequestExecution(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) {
        this.ctx = ctx;
        this.fullHttpRequest = fullHttpRequest;
    }

    @Override
    public void run() {

        FullHttpRequest request = fullHttpRequest;
        log.info(JSONObject.toJSONString(request));
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK, Unpooled.copiedBuffer("getinfo", CharsetUtil.UTF_8));
        System.out.println(response);
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);

    }

}
